package task;

/**
 * Created by lizhenyu on 2019/9/14
 */
public class RunnableTask {
    public static void main(String[] args) {
        // 通过Runnable实现三个窗口卖同一种票
        Runnable seller = new RunnableTicketSeller();

        Thread thread1 = new Thread(seller);
        Thread thread2 = new Thread(seller);
        Thread thread3 = new Thread(seller);

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class RunnableTicketSeller implements Runnable{
    private int num = 10;
    @Override
    public void run() {
        try {
            while (num > 0) {
                synchronized ((Object)num) {
                    if (num == 0) {
                        System.out.println("窗口 " + Thread.currentThread().getName() + " 票已卖完");
                        return;
                    }
                    System.out.println("窗口 " + Thread.currentThread().getName() + " 还有 " + num + " 张票");
                    num--;
                }
                Thread.sleep(1000);
            }
            System.out.println("窗口 " + Thread.currentThread().getName() + " 票已卖完");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}